//
//  ByLoginVC.m
//  caipiao_ios
//
//  Created by mc on 2018/7/4.
//  Copyright © 2018年 ZhangZhanbin. All rights reserved.
//

#import "ByLoginVC.h"
#import "WXApi.h"
#import "ByUserPerfectDataVC.h"


@interface ByLoginVC ()

@property (nonatomic, strong) UILabel *codeLable;

@end

@implementation ByLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addLeftBackBarButtonItem];
    
    
    
    [self initViews];
    
    //监听微信登陆
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getWeChatLoginCode:) name:@"weixinLogin" object:nil];
    
    // Do any additional setup after loading the view.
}
- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"weixinLogin" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    if (BY_USER) {
        [self leftItemsAction:0];
    }
   
}

- (void)initViews{
    UIImageView *backgroundView = [[UIImageView alloc] init];
    [self.view addSubview:backgroundView];
    [backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(0);
        make.right.equalTo(self.view).offset(0);
        if (@available(ios 11.0,*)) {
            make.top.equalTo(self.view.mas_safeAreaLayoutGuideTop).offset(0);
            make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom).offset(0);
        } else {
            make.top.equalTo(self.view).offset(0);
            make.bottom.equalTo(self.view).offset(0);
        }
    }];
    backgroundView.image = [UIImage imageNamed:@"beijing"];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backgroundView addSubview:leftBtn];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backgroundView).offset(10);
        make.top.equalTo(backgroundView).offset(15);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    [leftBtn setImage:[UIImage imageNamed:@"fanhuiyijijiemian"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftAction:) forControlEvents: UIControlEventTouchUpInside];
    
    
    UIImageView *iconView = [[UIImageView alloc] init];
    [backgroundView addSubview:iconView];
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backgroundView).offset(100);
        make.centerX.equalTo(backgroundView).offset(0);
        make.size.mas_equalTo(CGSizeMake(70, 70));
    }];
    iconView.layer.cornerRadius = 35;
    iconView.layer.masksToBounds = YES;
    iconView.image = [UIImage imageNamed:@"logo11"];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    [backgroundView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backgroundView).offset(10);
        make.right.equalTo(backgroundView).offset(-10);
        make.top.equalTo(iconView.mas_bottom).offset(20);
        make.height.mas_equalTo(@20);
    }];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"一张彩票，无限可能";
    titleLabel.font = FONT(18);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    UIControl *contorl = [[UIControl alloc] init];
    [backgroundView addSubview:contorl];
    [contorl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(backgroundView).offset(-150);
        make.left.equalTo(backgroundView).offset(30);
        make.right.equalTo(backgroundView).offset(-30);
        make.height.mas_equalTo(@40);
    }];
    contorl.layer.cornerRadius = 20;
    contorl.backgroundColor = [UIColor clearColor];
    contorl.layer.borderColor = [UIColor whiteColor].CGColor;
    contorl.layer.borderWidth = 1;
    backgroundView.userInteractionEnabled = YES;
    [contorl addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *wechatLabel = [[UILabel alloc] init];
    [contorl addSubview:wechatLabel];
    [wechatLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(contorl).offset(0);
        make.centerX.equalTo(contorl.mas_centerX).offset(50);
        make.size.mas_equalTo(CGSizeMake(150, 20));
    }];
    wechatLabel.textColor = [UIColor whiteColor];
    wechatLabel.text = @"微信登录";
    wechatLabel.textAlignment = NSTextAlignmentLeft;
    wechatLabel.font = FONT(16);
    
    UIImageView *wechatView = [[UIImageView alloc] init];
    [contorl addSubview:wechatView];
    [wechatView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(wechatLabel.mas_left).offset(-5);
        make.centerY.equalTo(contorl).offset(0);
        make.size.mas_equalTo(CGSizeMake(20, 20));
    }];
    wechatView.image = [UIImage imageNamed:@"weixin11111"];
    
    
    UILabel *codeLable = [[UILabel alloc] init];
    [backgroundView addSubview:codeLable];
    [codeLable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(contorl.mas_bottom).offset(20);
        make.left.equalTo(backgroundView).offset(20);
        make.right.equalTo(backgroundView).offset(-20);
        make.height.mas_equalTo(@30);
    }];
    codeLable.font = FONT(16);
    codeLable.textColor = [UIColor blackColor];
    codeLable.backgroundColor = [UIColor whiteColor];
    codeLable.textAlignment = NSTextAlignmentCenter;
    self.codeLable = codeLable;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showMenu)];
    [codeLable addGestureRecognizer:tap];
    codeLable.userInteractionEnabled = YES;
    codeLable.hidden = YES;
}




- (void)showMenu{
    [self becomeFirstResponder];
    UIMenuController *menu = [UIMenuController sharedMenuController];
    UIMenuItem *umiCopy = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copy1:)];
    [menu setMenuItems:@[umiCopy]];
    [menu setTargetRect:self.codeLable.frame inView:self.codeLable.superview];
    [menu setMenuVisible:YES animated:YES];
}

- (void)copy1:(id)sender {
    [[UIPasteboard generalPasteboard] setString:self.codeLable.text];
}

- (BOOL)canBecomeFirstResponder{
    return YES;
}


- (void)leftAction:(UIButton *)btn{
    [self leftItemsAction:0];
}




- (void)loginAction:(UIControl *)contorl{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:@"0" forKey:@"wechatCode"];
    [user synchronize];
    

    //构造SendAuthReq结构体
    SendAuthReq* req = [[SendAuthReq alloc ] init ];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123" ;
    //第三方向微信终端发送一个SendAuthReq消息结构
    [WXApi sendReq:req];
}



#pragma mark -- 微信登陆相关 --
-(void) onReq:(BaseReq*)req{
    DLog(@"onReq");
    
}

/*! @brief 发送一个sendReq后，收到微信的回应
 *
 * 收到一个来自微信的处理结果。调用一次sendReq后会收到onResp。
 * 可能收到的处理结果有SendMessageToWXResp、SendAuthResp等。
 * @param resp具体的回应内容，是自动释放的
 */
-(void) onResp:(BaseResp*)resp{
    
    DLog(@"onResp");
    
    if (resp == nil) {
        NSLog(@"不能为空!");
        return;
    }
    
    // 登陆
    if([resp isKindOfClass:[SendAuthResp class]]) {
        
        SendAuthResp *temp = (SendAuthResp*)resp;
        if (temp.errCode== 0) {
            
            NSString *code = temp.code;
            NSString *state = temp.state;
            
            NSDictionary *dictionary = @{@"code":code,@"state":state};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"weixinLogin" object:self userInfo:dictionary];
        }
    }
    
    
}

// 微信登陆通知方法
-(void)getWeChatLoginCode:(NSNotification *)notification{
    
    NSString *code = [[notification userInfo] objectForKey:@"code"];
    self.codeLable.text = code;
    ByNetParamsModel *paramsModel = [[ByNetParamsModel alloc] init];
    paramsModel.code = code;
    NSLog(@"code = %@", code);
    [ByCoreToolAlert showLoadind:@"登录中"];

    [ByApiUser  wechatIsRegister:paramsModel success:^(ByNetBaseResult *result) {
        [ByCoreToolAlert hideHud];
        NSLog(@"是否注册 = %@", result.data);
        NSDictionary *dic = result.data[@"data"];
        NSString *is_register = dic[@"is_register"];
        ByNetModel *netModel = [[ByNetModel alloc] initContentWithDic:dic];
        
        if (is_register.integerValue == 0) {
            
            ByUserPerfectDataVC *vc = [[ByUserPerfectDataVC alloc] init];
            vc.netModel = netModel;
            vc.dic = dic;
            [self by_normalPush:vc hasNavi:YES];
            
        }else{
          
            ByModelUser *user = [[ByModelUser alloc] initContentWithDic:dic];
            user.app_push = @"1";
            [ByCacheUser setUserInfo:user];
            
            // 登陆后缓存下支付方式
            [ByApiOther paySupportSuccess:^(ByNetBaseResult *result){
                
                NSLog(@"支付方式获取 = %@", result.data);
                NSArray *array = result.data[@"data"];
                NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
                NSData * data =  [NSKeyedArchiver archivedDataWithRootObject:array];
                [userDefaults  setObject:data forKey:KEY_Pay_Style];//存储设备列表
                [userDefaults synchronize];
                
            } failure:^(ByNetBaseResult *result) {
                [ByCoreToolAlert showFailureWithText:result.msg];
            }];
            [self leftItemsAction:0];
            
        }
        

    } failure:^(ByNetBaseResult *result) {
        [ByCoreToolAlert showFailureWithText:result.msg];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
